package com.zp.base.impl.labMaintenance;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zp.base.api.bo.ClinicItemDictBo;
import com.zp.base.api.vo.ClinicItemDictVo;
import com.zp.base.entity.labMaintenance.LabVsClinic;
import com.zp.base.entity.labMaintenance.bo.LabVsClinicBo;
import com.zp.base.entity.labMaintenance.vo.LabVsClinicVo;
import com.zp.base.mapper.labMaintenance.LabVsClinicMapper;
import com.zp.base.service.clinicItemDict.IClinicItemDictService;
import com.zp.base.service.labMaintenance.ILabVsClinicService;
import com.zp.common.core.constant.CacheNames;
import com.zp.common.core.utils.StringUtils;
import com.zp.common.myBatis.core.page.PageQuery;
import com.zp.common.myBatis.core.page.TableDataInfo;
import com.zp.common.redis.utils.CacheUtils;
import com.zp.system.api.entity.SysBaseDictData;
import com.zp.system.api.entity.SysDictData;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 检验项目与诊疗项目对照Service业务层处理
 *
 * @author zhang peng
 * @ date 2023-05-29
 */
@RequiredArgsConstructor
@Service
public class LabVsClinicServiceImpl implements ILabVsClinicService {

    private final LabVsClinicMapper baseMapper;

    private final IClinicItemDictService clinicItemDictService;

    /**
     * 检验管
     */
    static List<SysBaseDictData> labTubeMap = CacheUtils.get(CacheNames.SYS_BASE_DICT, CacheNames.LAB_TUBE);

    /**
     * 检验标本
     */
    static List<SysDictData> specimanDictMap = CacheUtils.get(CacheNames.SYS_DICT, CacheNames.SPECIMAN_DICT);

    /**
     * 查询检验项目与诊疗项目对照
     */
    @Override
    public LabVsClinicVo queryById(String id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询检验项目与诊疗项目对照列表(分页)
     */
    @Override
    public TableDataInfo<LabVsClinicVo> queryPageList(LabVsClinicBo bo, PageQuery pageQuery) {
        Page<LabVsClinicVo> result = baseMapper.selectVoPage(pageQuery.build(), bo);
        return TableDataInfo.build(result);
    }

    /**
     * 查询检验项目与诊疗项目对照列表(不分页)
     */
    @Override
    public List<LabVsClinicVo> queryList(LabVsClinicBo bo) {
        LambdaQueryWrapper<LabVsClinic> lqw = buildQueryWrapper(bo);
        lqw.eq(LabVsClinic::getDelFlag, "0");
        List<LabVsClinicVo> labTypeVos = baseMapper.selectVoList(lqw);
        ClinicItemDictBo clinicItemDictBo = new ClinicItemDictBo();
        clinicItemDictBo.setOrgId(bo.getOrgId());
        // 查询诊疗项目总价
        List<ClinicItemDictVo> clinicItemDictVos = clinicItemDictService.queryList(clinicItemDictBo);
        labTypeVos.forEach(labVsClinicVo -> {
            // 根据检查项目的项目id 获取 诊疗项目总价集合
            List<ClinicItemDictVo> collect = clinicItemDictVos.stream().filter(x -> StringUtils.equals(x.getClinicItemId(),
                    labVsClinicVo.getClinicId())).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(collect)) {
                labVsClinicVo.setTotalPrice(ObjectUtil.isNotNull(collect.get(0).getSubTotal()) ? collect.get(0).getSubTotal() : 0.00);
                labVsClinicVo.setItemName(collect.get(0).getItemName());
                labVsClinicVo.setItemCode(collect.get(0).getItemCode());
                labVsClinicVo.setInputCode(collect.get(0).getInputCode());
                if (CollectionUtils.isNotEmpty(specimanDictMap)) {
                    labVsClinicVo.setSpecimenName(
                            specimanDictMap.stream()
                                    .filter(i -> StringUtils.equals(labVsClinicVo.getSpecimen(), i.getDictValue()))
                                    .findAny().get().getDictLabel()
                    );
                }
                if (CollectionUtils.isNotEmpty(labTubeMap)) {
                    labVsClinicVo.setLabTubeName(
                            labTubeMap.stream()
                                    .filter(i -> StringUtils.equals(labVsClinicVo.getLabTube(), i.getValue()))
                                    .findAny().get().getLabel()
                    );
                }

            }
        });
        return labTypeVos.stream().filter(x -> StringUtils.isNotBlank(x.getItemName())).collect(Collectors.toList());

    }

    private LambdaQueryWrapper<LabVsClinic> buildQueryWrapper(LabVsClinicBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<LabVsClinic> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getLabId()), LabVsClinic::getLabId, bo.getLabId());
        lqw.eq(StringUtils.isNotBlank(bo.getClinicId()), LabVsClinic::getClinicId, bo.getClinicId());
        lqw.eq(StringUtils.isNotBlank(bo.getLabTube()), LabVsClinic::getLabTube, bo.getLabTube());
        lqw.eq(StringUtils.isNotBlank(bo.getSpecimen()), LabVsClinic::getSpecimen, bo.getSpecimen());
        lqw.eq(bo.getSort() != null, LabVsClinic::getSort, bo.getSort());
        lqw.eq(StringUtils.isNotBlank(bo.getPerformedBy()), LabVsClinic::getPerformedBy, bo.getPerformedBy());
        lqw.eq(bo.getCreateTime() != null, LabVsClinic::getCreateTime, bo.getCreateTime());
        lqw.eq(bo.getUpdateTime() != null, LabVsClinic::getUpdateTime, bo.getUpdateTime());
        lqw.eq(StringUtils.isNotBlank(bo.getRemarks()), LabVsClinic::getRemarks, bo.getRemarks());
        return lqw;
    }

    /**
     * 新增检验项目与诊疗项目对照
     */
    @Override
    public Boolean insertByBo(LabVsClinicBo bo) {
        LabVsClinic add = BeanUtil.toBean(bo, LabVsClinic.class);
        validEntityBeforeSave(add);
        add.initEntity();
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setVsId(add.getVsId());
        }
        return flag;
    }

    /**
     * 修改检验项目与诊疗项目对照
     */
    @Override
    public Boolean updateByBo(LabVsClinicBo bo) {
        LabVsClinic update = BeanUtil.toBean(bo, LabVsClinic.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(LabVsClinic entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除检验项目与诊疗项目对照
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
